package com.zyz.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyz.common.core.constants.CacheConstants;
import com.zyz.common.core.constants.Constants;
import com.zyz.common.core.enums.ExamListType;
import com.zyz.common.core.enums.ResultCodeEnum;
import com.zyz.common.redis.service.RedisService;

import com.github.pagehelper.PageHelper;
import com.zyz.common.security.exception.ServiceException;
import com.zyz.friend.mapper.exam.ExamMapper;
import com.zyz.friend.mapper.exam.ExamQuestionMapper;
import com.zyz.friend.mapper.userexam.UserExamMapper;
import com.zyz.friend.model.exam.Exam;
import com.zyz.friend.model.exam.ExamQuestion;
import com.zyz.friend.model.exam.dto.ExamQueryDTO;
import com.zyz.friend.model.exam.dto.ExamRankDTO;
import com.zyz.friend.model.exam.vo.ExamRankVO;
import com.zyz.friend.model.exam.vo.ExamVO;
import com.zyz.friend.model.userexam.UserExam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ExamCacheManager {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamQuestionMapper examQuestionMapper;

    public Long getListSize(Long examListType, Long userId) {
        String examListKey = getExamListKey(examListType, userId);
        return redisService.getListSize(examListKey);
    }

    public Long getExamQuestionListSize(Long examId) {
        String examQuestionListKey = getExamQuestionListKey(examId);
        return redisService.getListSize(examQuestionListKey);
    }


//
//    public Long getRankListSize(Long examId) {
//        return redisService.getListSize(getExamRankListKey(examId));
//    }

    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO, Long userId) {
        int start = (examQueryDTO.getPageNumber() - 1) * examQueryDTO.getPageSize();
        int end = start + examQueryDTO.getPageSize() - 1; //下标需要 -1
        String examListKey = getExamListKey(examQueryDTO.getType(), userId);
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        if (CollectionUtil.isEmpty(examVOList)) {
            //说明redis中数据可能有问题 从数据库中查数据并且重新刷新缓存
            examVOList = getExamListByDB(examQueryDTO, userId); //从数据库中获取数据
            refreshCache(examQueryDTO.getType(), userId);
        }
        return examVOList;
    }

    public void addUserExamCache(Long userId, Long examId) {
        redisService.leftPushForList(getUserExamKey(userId), examId);
    }

    public List<Long> getAllUserExamList(Long userId) {
        String userExamKey = getUserExamKey(userId);
        List<Long> userExamIdList = redisService.getCacheListByRange(userExamKey, 0, -1, Long.class);
        if (CollectionUtil.isNotEmpty(userExamIdList)) {
            return userExamIdList;
        }
        // 从数据库中查询
        List<UserExam> userExamByDB = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getUserId, userId));
        if (CollectionUtil.isEmpty(userExamByDB)) {
            return null;
        }
        // 刷新缓存
        refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
        userExamIdList = userExamByDB.stream().map(UserExam::getUserId).toList();
        log.info("userExamIdList: {}", userExamIdList);
        return userExamIdList;
    }

    //刷新缓竞赛存逻辑
    public void refreshCache(Long examListType, Long userId) {
//        log.info("刷新redis缓存 examListType:{}", examListType);
        List<Exam> examList = new ArrayList<>();
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            //查询未完赛的竞赛列表
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.PUBLISHED)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            //查询历史竞赛
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .le(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.PUBLISHED)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.USER_EXAM_LIST.getValue().equals(examListType)) {
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);
            examList = BeanUtil.copyToList(examVOList, Exam.class);
        }
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }

        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
//        log.info("存入redis中");
        redisService.multiSet(examMap);  //刷新详情缓存
        redisService.deleteObject(getExamListKey(examListType, userId)); // 把有问题的原本redis中的数据删除
        redisService.rightPushAll(getExamListKey(examListType, userId), examIdList);      //刷新列表缓存
    }


    // 刷新竞赛题目
    public void refreshExamQuestionList(Long examId) {
        // 从数据库中查询
        List<ExamQuestion> questionIdByDB = examQuestionMapper.selectList(new LambdaQueryWrapper<ExamQuestion>()
                .select(ExamQuestion::getQuestionId)
                .eq(ExamQuestion::getExamId, examId)
                .orderByAsc(ExamQuestion::getQuestionOrder));
        if (CollectionUtil.isEmpty(questionIdByDB)) {
            return;
        }
        String key = getExamQuestionListKey(examId);
        List<Long> questionIds = questionIdByDB.stream().map(ExamQuestion::getQuestionId).toList();
        // 同步到cache中
        redisService.rightPushAll(key, questionIds);
        // 设置一天的有效期
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(),
                LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
        redisService.expire(key, seconds, TimeUnit.SECONDS);
    }

    public Long getFirstQuestion(Long examId) {
        String key = getExamQuestionListKey(examId);
        return redisService.index(key, 0L, Long.class);
    }

    /**
     * 刷新竞赛排名缓存
     * @param examId  竞赛id
     */
    public void refreshRankCache(Long examId) {
        List<ExamRankVO> examRankListByDB = userExamMapper.selectExamRankList(examId);
        if (CollectionUtil.isEmpty(examRankListByDB)) {
            return;
        }
        // 刷新redis缓存
        redisService.rightPushAll(getExamRankListKey(examId), examRankListByDB);
    }

    public Long getPreQuestionId(Long examId, Long questionId) {
        String key = getExamQuestionListKey(examId);
        Long index = redisService.indexOf(key, questionId);
        if (index == null || index == 0) {
            log.warn("当前已经是第一题");
            throw new ServiceException(ResultCodeEnum.FAILED_QUESTION_FIRST);
        }
        return redisService.index(key, index - 1,Long.class);
    }

    public Long getNextQuestionId(Long examId, Long questionId) {
        String key = getExamQuestionListKey(examId);
        Long index = redisService.indexOf(key, questionId);
        if (getExamQuestionListSize(examId) - 1 == index) {
            log.warn("当前已经是最后一题");
            throw new ServiceException(ResultCodeEnum.FAILED_QUESTION_LAST);
        }
        return redisService.index(key, index + 1,Long.class);
    }


    public Long getRankListSize(Long examId) {
        String key = getExamRankListKey(examId);
        return redisService.getListSize(key);
    }

    /**
     * 从缓存中拿到rank竞赛排名
     * @param rankDTO
     * @return 竞赛排名
     */
    public List<ExamRankVO> getExamRankList(ExamRankDTO rankDTO) {
        int start = (rankDTO.getPageNumber() - 1) * rankDTO.getPageSize();
        int end = start + rankDTO.getPageSize() - 1;
        return redisService.getCacheListByRange(getExamRankListKey(rankDTO.getExamId()),start,end, ExamRankVO.class);
    }

    private List<ExamVO> getExamListByDB(ExamQueryDTO examQueryDTO, Long userId) {
        PageHelper.startPage(examQueryDTO.getPageNumber(), examQueryDTO.getPageSize());
        if (ExamListType.USER_EXAM_LIST.getValue().equals(examQueryDTO.getType())) {
            // 查询我的竞赛列表
            return userExamMapper.selectUserExamList(userId);
        } else {
            // 查询c端竞赛列表
            return examMapper.selectExamList(examQueryDTO);
        }
    }

    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if (CollectionUtil.isEmpty(examIdList)) {
            //说明redis当中没数据 从数据库中查数据并且重新刷新缓存
            return null;
        }
        //拼接redis当中key的方法 并且将拼接好的key存储到一个list中
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId));
        }
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
        CollUtil.removeNull(examVOList);
        if (CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()) {
            //说明redis中数据有问题 从数据库中查数据并且重新刷新缓存
            return null;
        }
        return examVOList;
    }

    private String getExamListKey(Long examListType, Long userId) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_HISTORY_LIST;
        } else {
            return CacheConstants.USER_EXAM_LIST + userId;
        }
    }

    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

    private String getUserExamKey(Long userId) {
        return CacheConstants.USER_EXAM_LIST + userId;
    }

    private String getExamQuestionListKey(Long examId) {
        return CacheConstants.EXAM_QUESTION_LIST + examId;
    }

    private String getExamRankListKey (Long examId) {
        return CacheConstants.EXAM_RANK_LIST + examId;
    }



}